package web;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    //创建一个排除列表,包含不需要登录就能访问的路径(如 "/login", "/register", "/public")。
     String public_urls[] = {"/login","/LoginServlet","/img","/css"};
     HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
     String url = req.getRequestURL().toString();

     //检查当前请求是否是对登录页面、注册页面或公共资源的请求。如果是,则允许请求通过。
     for(int i=0;i<public_urls.length;i++){
         if(url.contains(public_urls[i])){
             filterChain.doFilter(servletRequest, servletResponse);
             return;
         }
     }

     //如果不是上述情况,检查用户的 session 中是否存在表示已登录的属性
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user!=null){
            filterChain.doFilter(servletRequest, servletResponse);//如果用户已登录,允许请求继续
            return;
        }
        else{
        resp.sendRedirect("login.html");//否则返回登陆页面
        }

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
